package com.kly.chatter.api.application.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fqgj.base.services.redis.RedisClient;
import com.kly.sc.api.application.constant.ApiRedisKeys;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.chatter.response.UserChatterModeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class BaseService {

    @Autowired
    ChatterUserService chatterUserService;

    @Autowired
    RedisClient redisClient;

    private final static Integer ONE = 1;

    public boolean getModeUserCode(String userCode, String modeUserCode) {
        String jsonStr = redisClient.get(ApiRedisKeys.CHATTER_MODE_USER_CODE.getValue(), userCode);
        if (StringUtils.isNotEmpty(jsonStr)) {
            JSONObject jsonObject = JSONUtil.parseObj(jsonStr.trim());
            if (jsonObject.getStr(modeUserCode) != null) {
                return true;
            }
        }
        return checkAndUpdateModeList(userCode, modeUserCode);
    }

    private boolean checkAndUpdateModeList(String userCode, String modeUserCode) {
        Map<String, UserChatterModeDto> modeList = chatterUserService.getModeList(userCode);
        if (modeList.get(modeUserCode) != null) {
            Long seconds = getSeconds(ONE);
            String toJsonStr = JSONUtil.toJsonStr(modeList);
            redisClient.set(ApiRedisKeys.CHATTER_MODE_USER_CODE.getValue(), toJsonStr, seconds, userCode);
            return true;
        }
        return false;
    }

    public Map<String, UserChatterModeDto> getModeMap(String userCode){
        return chatterUserService.getModeList(userCode);
    }


    /**
     * 获取当前日期到days天之后的秒数
     *
     * @param days 指定天数
     */
    public Long getSeconds(Integer days) {
        // 获取1天后0点的时间
        DateTime endTimeInOneDays = DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), days));
        DateTime nowTime = DateUtil.date();
        return DateUtil.between(nowTime, endTimeInOneDays, DateUnit.SECOND, false);
    }
}
